package com.wandian.cqcsk.mvvm.mine.helpandsuggest.helpsuggest;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.utils.ActivityUtil;
import com.mylib.libcore.utils.BitMapUtils;
import com.mylib.libcore.utils.FileUtil;
import com.mylib.libcore.utils.MyGlideEngine;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.libcore.utils.ViewUtils;
import com.wandian.cqcsk.R;
import com.wandian.cqcsk.adapter.mine.HelpSuggestPicRecycleAdapter;
import com.wandian.cqcsk.databinding.ActivityHelpSuggestBinding;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description 用户建议
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_HELP_SUGGEST)
public class HelpSuggestActivity extends BaseMVVMActivity<HelpSuggestViewModel> {
    private ActivityHelpSuggestBinding dataBinding;
    private HelpSuggestPicRecycleAdapter helpSuggestPicRecycleAdapter;
    private ArrayList<String> copyList=new ArrayList<>();
    private ArrayList<String> compressImgPath= new ArrayList<>();
    private int chooseIndexCopyImg = 0;
    private int chooseType = 101;
    private String sendText = "";
    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_help_suggest);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        initViewData();
        initRecycle();
        initClink();
    }

    private void initViewData(){
        ActivityUtil.getInstance().showStatusView(this,dataBinding.viewSysTop,true);
        dataBinding.bindTransparentToolBar.toolBarTvTitle.setText("反馈");
        dataBinding.bindTransparentToolBar.toolBarTitleRight.setVisibility(View.VISIBLE);
        dataBinding.bindTransparentToolBar.toolBarTitleRight.setText("提交");

        mViewModel.oosBean.observe(this,oosBean->{
            if(!UIUtils.isEmpty(oosBean)){
                mViewModel.upLoadImg(this,oosBean,  compressImgPath,sendText);
            }else {
                mViewModel.sendSuggest(sendText,"");
            }
        });
    }

    private void initClink(){
        dataBinding.bindTransparentToolBar.toolBarIvBack.setOnClickListener(v -> {
            finishhideSoftBoard();
            finish();
        });
        //提交
        dataBinding.bindTransparentToolBar.toolBarTitleRight.setOnClickListener(v -> {
            finishhideSoftBoard();
            if(UIUtils.isEmpty(dataBinding.etContent.getText()) || UIUtils.isEmpty(dataBinding.etContent.getText().toString().trim())){
                ToastUtil.show("请描述您的问题");
                return;
            }else {
                sendText = dataBinding.etContent.getText().toString().trim();
            }

            if(!UIUtils.isEmpty(dataBinding.etLxfs.getText()) && !UIUtils.isEmpty(dataBinding.etLxfs.getText().toString().trim()))
                sendText =sendText+ "\n联系方式："+dataBinding.etLxfs.getText().toString().trim();
            if(compressImgPath.size()>0){
                mViewModel.getOOSToken();
            }else {
                mViewModel.sendSuggest(sendText,"");
            }
        });
    }

    private void initRecycle(){
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this,2);
        dataBinding.recyclePic.setLayoutManager(layoutManager);
        helpSuggestPicRecycleAdapter = new HelpSuggestPicRecycleAdapter(R.layout.item_report_copy_img_style);
        dataBinding.recyclePic.setAdapter(helpSuggestPicRecycleAdapter);
        copyList.clear();
        copyList.add(null);
        copyList.add(null);
        helpSuggestPicRecycleAdapter.setNewData(copyList);
        helpSuggestPicRecycleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                chooseIndexCopyImg =position;
                initCamer(101);
            }
        });
    }

    private void initCamer(int type) {
        chooseType =type;
        boolean isAllGranted = checkPermissionAllGranted(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE});
        if (isAllGranted) {
            initPhoto(type);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, type);
        }
    }

    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == chooseType) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initPhoto(chooseType);
            }
        }
    }

    private void initPhoto(int type) {
        Matisse.from(this)
                .choose(MimeType.ofAll()) // 选择 mime 的类型
                .countable(true)
                .maxSelectable(1) // 图片选择的最多数量
                .originalEnable(false)
                .maxOriginalSize(5)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.dp_120))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new MyGlideEngine()) // 使用的图片加载引擎
                .theme(R.style.Matisse_Dracula)
                .capture(true) //是否提供拍照功能
                .autoHideToolbarOnSingleTap(true)
                .captureStrategy(new CaptureStrategy(true, mContext.getPackageName() + ".provider"))//存储到哪里
                .forResult(type);// 设置作为标记的请求码
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("onActivityResult",requestCode+"==="+resultCode);
        if (resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            Bitmap bitmap = BitMapUtils.getBitmapFromUri(HelpSuggestActivity.this, mSelected.get(0));
            if(!UIUtils.isEmpty(bitmap)){
                if(requestCode==101){
                    if(!UIUtils.isEmpty(bitmap)){
                        //压缩图片
                        String path = FileUtil.getCompressFilePath(bitmap);
                        if(!UIUtils.isEmpty(compressImgPath) && compressImgPath.size()>=2 && chooseIndexCopyImg<compressImgPath.size()){
                            compressImgPath.set(chooseIndexCopyImg,path);
                        }else {
                            compressImgPath.add(path);
                        }
                        if(copyList.size()>chooseIndexCopyImg) copyList.set(chooseIndexCopyImg,path);
                        else  copyList.add(path);
                        helpSuggestPicRecycleAdapter.setNewData(copyList);
                    }

                }
            }else {
                ToastUtil.show("图片获取失败");
            }

        }
    }

    @Override
    protected void onDestroy() {
        finishhideSoftBoard();
        super.onDestroy();
    }
}
